<?php

namespace App\Services;

use App\Entity\AreaEntity;
use App\Models\Area as AreaModel;
use App\Models\UserAddress;
use App\Utils\Tool;

class UserAddressService
{
    // 获取该人的默认地址信息条
    public static function getdefault($uid)
    {
        return UserAddress::query()
            ->where('user_id', '=', $uid)
            ->where('isdefault', '=', 1)
            ->first();
    }

    /**
     * 服务地址添加
     * @param int $userId
     * @param $address
     */
    public static function add(int $userId, $address)
    {
        $address['user_id'] = $userId;
        $address['address'] = self::filterAddrStr($address['address']);
        // 如果有经纬度，计算百度系、腾讯系经纬度
        if (!empty($address['lng']) && !empty($address['lat'])) {
            $address['gd_lng'] = $address['lng'];
            $address['gd_lat'] = $address['lat'];
            $lnglat = Tool::tengxunToBaidu($address['lng'], $address['lat']);
            $address['lng'] = $lnglat['lng'];
            $address['lat'] = $lnglat['lat'];
        } else {
            unset($address['lng']);
            unset($address['lat']);
        }
        $newAddr = new UserAddress($address);
        $newAddr->save($address);
        if ($address['isdefault'] == 1) { // 当前默认就得把别的地址设置为非默认
            UserAddress::query()
                ->where('user_id', '=', $userId)
                ->where('id', '<>', $newAddr->id)
                ->update(['isdefault' => 0]);
        }
    }

    /**
     * 已存在地址的修改
     * @param $userId
     * @param $address
     */
    public static function update($userId, $address)
    {
        $address['address'] = self::filterAddrStr($address['address']);
        $userAddress = UserAddress::query()->find($address['id']);
        // 如果有经纬度，计算百度系、腾讯系经纬度
        if (!empty($address['lng']) && !empty($address['lat'])) {
            $address['gd_lng'] = $address['lng'];
            $address['gd_lat'] = $address['lat'];
            $lnglat = Tool::tengxunToBaidu($address['lng'], $address['lat']);
            $address['lng'] = $lnglat['lng'];
            $address['lat'] = $lnglat['lat'];
        } else {
            $address['gd_lng'] = '';
            $address['gd_lat'] = '';
            $address['lng'] = '';
            $address['lat'] = '';
        }
        $userAddress->update($address);
    }

    /**
     * 地址设置成默认地址
     * @param $userId
     * @param $addressID
     */
    public static function setDefault($userId, $addressID)
    {
        UserAddress::query()
            ->where('user_id', '=', $userId)
            ->where('id', '<>', $addressID)
            ->update(['isdefault' => 0]); //非自己都设置成非默认
        $userAddress = UserAddress::query()->find($addressID);
        $userAddress->update([
            'isdefault' => 1,
        ]); // 把自己改成默认（也许自己本来就是默认就不会执行sql了）
    }

    private static function filterAddrStr($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str
        );
        $str = trim(mb_substr($str, 0, 50, 'utf-8'));
        return $str;
    }

    public static function miniAddr2OldAddress(array $address): array
    {
        $miniAddrCity = $address['miniaddr_city'] ?? '';
        $miniAddrDistrict = $address['miniaddr_district'] ?? '';
        if (!$miniAddrCity) {
            return [201, '必要参数 miniaddr_city 缺失或为空', []];
        }
        if (!$miniAddrDistrict) {
            return [202, '必要参数 miniaddr_district 缺失或为空', []];
        }
        $cityAreaModel = AreaModel::where(['areaname' => $miniAddrCity, 'level' => 1])->first();
        $districtAreaModel = AreaModel::where(['areaname' => $miniAddrDistrict, 'level' => 2])->first();
        if (!$cityAreaModel || !$districtAreaModel) {
            return [203, '城市或城区参数无法正确转换', []];
        }
        $cityAreaEntity = new AreaEntity($cityAreaModel);
        $districtAreaEntity = new AreaEntity($districtAreaModel);
        $address['proviceid'] = $cityAreaEntity->getId();
        $address['province'] = $cityAreaEntity->getAreaname();
        $address['cityid'] = $districtAreaEntity->getId();
        $address['city'] = $districtAreaEntity->getAreaname();
        $address['districtid'] = 0;
        $address['district'] = '';
        return [0, 'ok', $address];
    }

    public static function getUserOneAddressInfo(int $id, int $userId): ?UserAddress
    {
        return UserAddress::where(['id' => $id, 'user_id' => $userId])->first();
    }
}
